import 'dart:math';

import 'package:audio_waveforms/audio_waveforms.dart';
import 'package:flutter/material.dart';
import 'package:hockey/jzx_apps.dart';
import 'package:hockey/jzx_models.dart';
import 'package:hockey/services/jzx_config.dart';
import 'package:hockey/services/jzx_user.dart';
import 'package:hockey/widgets/dialogs/jzx_options_sheet.dart';

import '../../models/jzx_comment_data.dart';

class JzxPostDetailController extends GetxController {
  var item = const JzxMediaData().obs;
  late String uid;

  var isFollow = false.obs;

  final text = TextEditingController();

  /// 留言
  var comments = <JzxCommentData>[].obs;
  // 获取聊天ID，这里通过帖子ID进行构建，不同帖子对应不同的聊天记录
  String postId = '';

  /// 播放器
  PlayerController player = PlayerController(); // Initialise

  /// index
  var swiperCur = 0.obs;

  ///

  @override
  void onInit() async {
    item.value = Get.arguments as JzxMediaData;
    uid = item.value.user.userId;
    postId = item.value.id.toString();
    //
    isFollow.value = JzxConfigService.to.isFollow(uid);
    super.onInit();

    getMessages();
  }

  @override
  onClose() {
    player.dispose();
    super.onClose();
  }

  /// 获取聊天记录
  getMessages() async {
    comments.value = JzxConfigService.to.getCommentListById(postId);
  }

  void showOptions() {
    Get.bottomSheet(
      JzxOptionsSheet(
        uid,
        onFollow: () {
          isFollow.toggle();
        },
        onBlock: () {
          isFollow.value = false;
          Get.back();
        },
      ),
      backgroundColor: Colors.white,
      isScrollControlled: true,
      barrierColor: myAppColors.barrierColor,
    );
  }

  void likeOrCancel() {
    final state = item.value.isLiked;
    //
    if (state == false) {
      JzxUserService.to.updateUnlockConditions(2);
    }
    item.value = item.value.copyWith(
      isLiked: !state,
      like: item.value.like + (state ? -1 : 1),
    );

    JzxConfigService.to.updatePostList(item.value, canRefresh: true);
  }

  void followAct() {
    JzxNetRepository.client.addFollow({'followUserId': uid});
    JzxConfigService.to.updateFollows(uid);
    showMessage(
        isFollow.value ? 'Unfollow Successfully' : 'Follow Successfully');

    isFollow.toggle();
  }

  sendText() {
    if (text.text.trim().isEmpty) {
      showMessage('ideas cannot be empty');
      text.clear();
      return;
    }
    Get.context?.keyboardDissmiss();
    sendComment(text.text);
  }

  /// 发送留言
  void sendComment(String content, {int type = 0}) async {
    // JzxRCloudService.to.sendText(text.text);
    showLoading();
    await (Random().nextInt(2) + 1).delay();
    hideLoading();

    JzxCommentData item = JzxCommentData(
      content: content,
      postId: postId,
      id: '$postId-${JzxConfigService.to.commentsList.length + 1}',
      userId: JzxUserService.to.uid,
      nickname: JzxUserService.to.nickname,
      avatar: JzxUserService.to.avatar,
      level: JzxUserService.to.userWear.value,
      type: type,
    );

    comments.insert(0, item);
    JzxConfigService.to.updateCommentList(item);

    text.clear();
  }

  void likeComment(JzxCommentData item, int index) {
    comments[index] = item.copyWith(
      isLiked: !item.isLiked,
      like: item.like + (item.isLiked ? -1 : 1),
    );
    JzxConfigService.to.updateCommentList(comments[index]);
  }
}

// extension on RCIMIWMessage {
//   /// 转换成本地数据类型
//   JzxCommentData get toComment {
//     var item = JzxCommentData(
//       id: '$messageId',
//       userId: '$senderUserId',
//       nickname: JzxUserService.to.nickname,
//       avatar: JzxUserService.to.avatar,
//       level: JzxUserService.to.userWear.value,
//       isLiked: JzxConfigService.to.isCommentLike('$targetId-$messageId'),
//     );

//     if (this is RCIMIWTextMessage) {
//       item = item.copyWith(
//         content: (this as RCIMIWTextMessage).text ?? '',
//         type: 0,
//       );
//     } else if (this is RCIMIWVoiceMessage) {
//       item = item.copyWith(
//         content: (this as RCIMIWVoiceMessage).remote ?? '',
//         type: 1,
//       );
//     }

//     return item;
//   }
// }
